package command

import (
	"codejy/structdef"
	"codejy/utils"
	"flag"
)

type command interface {
	//绑定
	Bind()
	//满足条件
	Condition() bool
	//执行命令
	Execute(threadStore *structdef.ThreadStore)
	//获取命令名称
	GetName() string

	//获取命令描述
	GetDesc() string
	//优先级  ,0最低...
	GetPriority() int
	//是否终止
	IsExit() bool
}

var commands = []command{}

// 注册命令
func RegisterCommand(c command) {
	//判断是否已经存在
	for _, v := range commands {
		if v.GetName() == c.GetName() {
			panic("命令已注册过了")
		}
	}
	commands = append(commands, c)
	//按照优先级排序,从大到小
	utils.SortSlice[command](&commands, 1, func(i, j command) int {
		return i.GetPriority() - j.GetPriority()
	})
}

// 执行命令
func ExecuteCommand(threadStore *structdef.ThreadStore) {
	//绑定参数
	for _, v := range commands {
		v.Bind()
	}
	//解析参数
	flag.Parse()
	//执行满足条件的命令
	for _, v := range commands {
		if v.Condition() {
			v.Execute(threadStore)
			if v.IsExit() {
				break
			}
		}
	}
}
